package com.gmail.hy87cn.hellohi.client;

import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;

public class HiTitle {
	public HiTitle() {
		timer = new Timer() {
			@Override
			public void run() {
				update();
			}
		};
	}
	
	private static String originalTitle = Window.getTitle();
	private String title;
	
	private int tick = 0;
	private static int MAX_TICK = 20;
	private static int LENGTH = 24;
	private static int PERIOD = 500; //ms
	private Timer timer;
	
	public void setTitle(String title) {
		HTML html = new HTML();
		html.setHTML(title);
		this.title = "________________________" + html.getText().trim() + "________________________";
		tick = 0;
		update();
		timer.scheduleRepeating(PERIOD);
	}
	
	public String getTitle() {
		return title;
	}
	
	private void update() {
		int begin = tick++ * (title.length() - LENGTH) / MAX_TICK;
		Window.setTitle(title.substring(begin, begin + LENGTH));
		if (tick >= MAX_TICK) {
			Window.setTitle(originalTitle);
			timer.cancel();
		}
	}
}
